﻿using DataAccessLayer;
using DBStoreWorkerRole.Contracts;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace DBStoreWorkerRole.Operations
{
    class TempDBStoreProcessing
    {
        SensorEntity sensorDB = new SensorEntity();
        DeviceEntity deviceDb = new DeviceEntity();
        private Object thisLock = new Object();

        public void dataLogging_BL(TempDataLog receivedMessage)
        {
            
         
            Debug.Print("Payload:");
            Debug.Print("DeviceID:" + receivedMessage.deviceId);
            Debug.Print("SensorID" + receivedMessage.sensorId);
            Debug.Print("Data:" + receivedMessage.data);
            #region Deserialization example
            //MemoryStream stream1 = new MemoryStream();
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Data>));
            //ser.WriteObject(stream1, receivedMessage.data);
            //stream1.Position = 0;
            //StreamReader sr = new StreamReader(stream1);
            //string text = sr.ReadToEnd();
            //String data = "{\"data\":" + text + "}";
            //   Debug.Print("Received Data:" + data);
#endregion

               JavaScriptSerializer js = new JavaScriptSerializer();
               string text = js.Serialize(receivedMessage.data);
               String data = "{\"data\":" + text + "}";

         
            try
            {
                string sensortype = sensorDB.getTypeById_DAL(receivedMessage.sensorId);

                Dictionary<string, string> result = deviceDb.getConnectionStringAndDB_DAL(receivedMessage.deviceId);
          
                Mongo mongoDB = new Mongo(result["connectionString"], result["databaseName"]);

                System.Diagnostics.Trace.WriteLine("Calling MONGO_DAL");
                mongoDB.deserialiseAndInsertDocument_DAL(data, receivedMessage.sensorId, sensortype);
                
            }
            catch (Exception ex)
            {

            }
            
              

     
        }

        public void StoreData_BL(String message,int deviceid, int sensorId)
        {

            try
            {
                string sensortype = sensorDB.getTypeById_DAL(sensorId);

                Dictionary<string, string> result = deviceDb.getConnectionStringAndDB_DAL(deviceid);

                Mongo mongoDB = new Mongo(result["connectionString"], result["databaseName"]);

                System.Diagnostics.Trace.WriteLine("Calling MONGO_DAL");
                mongoDB.deserialiseAndInsertDocument_DAL(message, sensorId, sensortype);
            }
            catch (Exception ex)
            {

            }

        }
    }
}
